package com.story.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class StoryApplicationContext {

    private Class configClass;
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, Object> signletonBeanMaps = new ConcurrentHashMap<>();
    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public StoryApplicationContext(Class configClass)  {
        this.configClass = configClass;
        // 扫描路径
        if(configClass.isAnnotationPresent(ComponentScan.class)){
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();    // 扫描路径 com.story.service

            path = path.replace(".","/");   // com.story.service

            ClassLoader classLoader = configClass.getClassLoader();
            URL url = classLoader.getResource(path);

            File file = new File(url.getFile());
//            System.out.println(file);
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for(File f : files){
                    String filename = f.getAbsolutePath();
//                    System.out.println(filename);
                    // 判断类是不是一个bean
                    if(filename.endsWith(".class")){
                        String className = filename.substring(filename.indexOf("com"),filename.indexOf(".class"));
                        className = className.replace("\\",".");
//                        System.out.println(className);
                        try {
                            Class<?> clazz = classLoader.loadClass(className);
                            if (clazz.isAnnotationPresent(Component.class)) {

                                if(BeanPostProcessor.class.isAssignableFrom(clazz)){
                                    BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorList.add(beanPostProcessor);
                                }


                                // 是一个bean : 单例bean/多例bean   BeanDefinition
                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();
                                if(beanName.equals("")){
                                    // 类名---> 进行首字母小写
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);

                                if(clazz.isAnnotationPresent(Scope.class)){
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                }else{
                                    beanDefinition.setScope("singleton");
                                }
//                                System.out.println(clazz);

                                beanDefinitionMap.put(beanName, beanDefinition);

                                // 单例bean
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            throw new RuntimeException(e);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }

                    }
                }
            }
        }
        // 实例化单例bean
        for(String beanName : beanDefinitionMap.keySet()){
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){

                Object bean = createBean(beanName, beanDefinition);
                signletonBeanMaps.put(beanName, bean);

            }
        }

    }
    private Object createBean(String beanName, BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();
            for(Field declaredField : clazz.getDeclaredFields()){
                // 依赖注入
                if(declaredField.isAnnotationPresent(Autowired.class)){
                    declaredField.setAccessible(true);
                    declaredField.set(instance,getBean(declaredField.getName()));
                }
            }

            // Aware   ---  回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            // BeanPostProcessor --- postProcessBeforeInitialization
            for(BeanPostProcessor beanPostProcessor : beanPostProcessorList){
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName,instance);
            }

            // 初始化   ---  初始化
            if(instance instanceof InitializingBean){
                ((InitializingBean)instance).afterPropertiesSet();
            }

            // BeanPostProcessor --- postProcessAfterInitialization
            for(BeanPostProcessor beanPostProcessor : beanPostProcessorList){
                instance = beanPostProcessor.postProcessAfterInitialization(beanName,instance);
            }

            // 初始化   --- AOP
            return instance;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

    }
    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if(beanDefinition == null){
            throw new NullPointerException();
        }else{
            String scope = beanDefinition.getScope();
            if(scope.equals("singleton")){
                Object bean = signletonBeanMaps.get(beanName);
                if(bean == null){
                    Object bean1 = createBean(beanName, beanDefinition);
                    // 创建之后 放入单例池
                    signletonBeanMaps.put(beanName, bean1);
                }
                return bean;
            }else{
                return createBean(beanName, beanDefinition);
            }
        }

    }

}
